from requests import Request
from rest_framework.decorators import api_view
from rest_framework.exceptions import ValidationError
from rest_framework.response import Response

import api.utils.sms as sms_util
from api.serializers.sms_serializer import SmsSerializer, SmsValidateSerializer


@api_view(['POST'])
def get_sms_code(request: Request):
    serializer = SmsSerializer(data=request.data)
    if serializer.is_valid():
        sms_util.send_sms(serializer.validated_data['phone'])
        return Response({'detail': u'短信发送成功'})
    else:
        raise ValidationError(serializer.errors)


@api_view(['POST'])
def validate_sms_code(request: Request):
    serializer = SmsValidateSerializer(data=request.data)
    if serializer.is_valid():
        phone = serializer.validated_data['phone']
        sms_code = serializer.validated_data['sms_code']
        if sms_util.validate_sms_code(phone, sms_code):
            return Response({'detail': u'验证码正确'})
        else:
            raise ValidationError(u"验证码不正确或已失效")
    else:
        raise ValidationError(serializer.errors)
